import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'

NProgress.configure({ showSpinner: false })

function hasPermission(roles, permissionRoles) {
  if (roles.includes('admin')) return true
  if (!permissionRoles) return true
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

const whiteList = ['/login'] // 不重定向白名单

router.beforeEach((to, from, next) => {
  NProgress.start()
  // console.log('进入路由守卫')
  // console.log(getToken())
  if (getToken()) {
    // console.log('有token')
    if (to.path === '/login') {
      // 如果去登录页面则直接进home页面
      // console.log('没必要去登录页面 去主页面')
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      // console.log('判断用户是否已经获取role信息')
      if (store.getters.roles.length === 0) {
        // console.log('没有获取role 准备获取')
        store.dispatch('GetUserInfo').then(res => {
          // console.log('GetUserInfo:', res)
          var userRole = []
          for (const role of res.data.roles) {
            userRole.push(role)
          }
          // console.log('userRole:', userRole)

          store.dispatch('GenerateRoutes', userRole).then(accessRoutes => {
            // console.log('accessRoutes', accessRoutes)
            router.addRoutes(accessRoutes)
            next({
              ...to,
              replace: true
            })
          })
        }).catch(err => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err)
            next({
              path: '/'
            })
          })
        })
      } else {
        // console.log('已经获取role', store.getters.roles)
        if (hasPermission(store.getters.roles, to.meta.roles)) { // 用户拥有的权限 要跳转的页面所需的权限
          // console.log('to:', to)
          // console.log('有权限 放行')
          next()
        } else {
          // console.log('没有权限 去404')
          next({
            path: '/404'
          })
        }
      }
    }
  } else {
    // console.log('没有token')
    if (whiteList.indexOf(to.path) !== -1) {
      // console.log('在白名单里 放行')
      next()
    } else {
      // console.log('没有在白名单 需要登录')
      next('/login')
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
